<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="网关名称" prop="gatewayName">
        <el-input
          v-model="queryParams.gatewayName"
          placeholder="请输入网关名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="网关类型" prop="provider">
        <el-select v-model="queryParams.provider" placeholder="请选择网关类型" clearable>
          <el-option
            v-for="dict in providers"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="启停状态" prop="startState">
        <el-select v-model="queryParams.startState" placeholder="请选择启停状态" clearable>
          <el-option
            v-for="dict in startState"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['iot:deviceGateway:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['iot:deviceGateway:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['iot:deviceGateway:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="deviceGatewayTable" v-loading="loading" :data="deviceGatewayList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="网关名称" align="center" prop="gatewayName" />
      <el-table-column label="网关类型" align="center" prop="provider">
        <template slot-scope="scope">
          {{ getTableProvider(scope.row.provider) }}
        </template>
      </el-table-column>
      <el-table-column label="启停状态" align="center" prop="startState">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.startState"
            active-value="enabled"
            inactive-value="disabled"
            @change="handleStartStopChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="description"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['iot:deviceGateway:edit']"
          >修改</el-button>
          <el-button
            v-if="scope.row.startState === 'disabled'"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iot:deviceGateway:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备网关对话框 -->
    <el-drawer
      :wrapperClosable="false"
      :title="title"
      :visible.sync="open"
      direction="rtl"
    >
      <el-container>
        <el-main>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">

            <!-- 网关名称 -->
            <el-form-item label="网关名称" prop="gatewayName">
              <el-input v-model="form.gatewayName" placeholder="请输入网关名称"/>
            </el-form-item>

            <!-- 网关类型 -->
            <el-form-item label="网关类型" prop="provider">
              <el-select
                v-model="form.provider"
                :disabled="disabledByStartState"
                placeholder="请选择网关类型"
                class="select-width"
              >
                <el-option
                  v-for="dict in providers"
                  :key="dict.value"
                  :label="dict.name"
                  :value="dict.id"
                ></el-option>
              </el-select>
            </el-form-item>

            <!-- 网络组件 -->
            <el-form-item label="网络组件" prop="networkId">
              <el-select
                v-model="form.networkId"
                :disabled="disabledByStartState"
                placeholder="请选择网络组件"
                class="select-width"
              >
                <el-option
                  v-for="dict in networkConfig"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.id"
                ></el-option>
              </el-select>
            </el-form-item>

            <!-- 消息协议 -->
            <el-form-item
              v-if="protocolVisible"
              :label="form.provider === 'mqtt-server-gateway'? '认证协议': '消息协议'"
              prop="configuration.protocol"
            >
              <el-select
                v-model="form.configuration.protocol"
                :disabled="disabledByStartState"
                placeholder="请选择消息协议"
                class="select-width"
              >
                <el-option
                  v-for="dict in protocols"
                  :key="dict.id"
                  :label="dict.protocolName"
                  :value="dict.id"
                ></el-option>
              </el-select>
            </el-form-item>

            <!-- Topics -->
            <el-form-item v-if="topicsVisible" label="Topics" prop="configuration.topics">
              <el-input
                v-model="form.configuration.topics"
                :disabled="disabledByStartState"
                type="textarea"
                placeholder="请输入内容"
              />
            </el-form-item>

            <!--Qos-->
            <el-form-item v-if="qosVisible" label="Qos" prop="configuration.qos">
              <template>
                <el-radio :disabled="disabledByStartState" v-model="form.configuration.qos" label="1">0</el-radio>
                <el-radio :disabled="disabledByStartState" v-model="form.configuration.qos" label="2">1</el-radio>
                <el-radio :disabled="disabledByStartState" v-model="form.configuration.qos" label="3">2</el-radio>
              </template>
            </el-form-item>

            <!-- 描述 -->
            <el-form-item label="描述" prop="description">
              <el-input v-model="form.description" type="textarea" placeholder="请输入内容"/>
            </el-form-item>

          </el-form>

        </el-main>
        <el-footer>
          <div class="bottom-bar" style="text-align: right">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
          </div>
        </el-footer>
      </el-container>
    </el-drawer>

  </div>
</template>

<script>
import {
  listDeviceGateway,
  getDeviceGateway,
  addDeviceGateway,
  editDeviceGateway,
  removeDeviceGateway,
  startupDeviceGateway,
  shutdownDeviceGateway,
  getProviders
} from '@/api/iot/deviceGateway'
import { queryProtocol } from '@/api/iot/protocol'
import { queryNetwork } from '@/api/iot/network'

import Editor from 'vue2-ace-editor'

export default {
  name: 'DeviceGateway',
  components: {
    Editor
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备网关表格数据
      deviceGatewayList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        gatewayName: null,
        startState: null,
        provider: null
      },
      providers: [],
      providerMap: {},
      networkConfig: [],
      protocols: [],
      startState: [{
        value: 'disabled',
        label: '未启动'
      }, {
        value: 'enabled',
        label: '已启动'

      }],
      // 表单参数
      form: {
        //其他配置
        configuration: {}
      },

      // 设备网关名称下拉框默认隐藏
      protocolVisible: false,
      // topics输入框默认隐藏
      topicsVisible: false,
      // Qos选择器默认隐藏
      qosVisible: false,

      // 表单校验
      rules: {
        gatewayName: [
          { required: true, message: '网关名称不能为空', trigger: 'blur' }
        ],
        provider: [
          { required: true, message: '网关类型不能为空', trigger: 'blur' }
        ],
        networkId: [
          { required: true, message: '网络组件不能为空', trigger: 'change' }
        ],
        configuration: {
          protocol: [
            { required: true, message: '消息协议不能为空', trigger: 'change' }
          ]
        }
      }
    }
  },
  computed: {
    disabledByStartState() {
      return this.form.startState === 'enabled'
    }
  },
  watch: {
    'form.provider'(newType, oldType) {
      this.visibleByDeviceGatewayType(newType)
      this.getNetwork()
      if (newType && oldType) {
        this.resetNetworkSelect()
      }
    }
  },
  created() {
    this.getProviders().then(data => {
      this.setProviderMap(data)
      this.getList()
      this.getProtocols()
    })
  },
  methods: {
    /** 查询设备网关列表 */
    getList() {
      this.loading = true
      listDeviceGateway(this.queryParams).then(response => {
        this.deviceGatewayList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        //网络组件ID
        networkId: null,
        //网关类型
        provider: null,
        //网关名称
        gatewayName: null,
        //其他配置
        configuration: {},
        //启停状态
        startState: null,
        //描述
        description: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      selection.forEach(row => {
        if (row.publishState === 1) {
          this.$refs.deviceGatewayTable.toggleRowSelection(row)
        }
      })
      this.ids = selection.map(item => item.id)
      this.names = selection.map(item => item.gatewayName)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加设备网关'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getDeviceGateway(id).then(response => {
        let data = response.data
        data.configuration = JSON.parse(data.configuration)
        this.form = data
        this.open = true
        this.title = '修改设备网关'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          let form = JSON.parse(JSON.stringify(this.form))
          form.configuration = JSON.stringify(form.configuration)
          if (this.form.id != null) {
            editDeviceGateway(form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addDeviceGateway(form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      const names = row.gatewayName || this.names
      this.$modal.confirm('是否确认删除网关名称为"' + names + '"的数据项？').then(function() {
        return removeDeviceGateway(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('iot/device-gateway/export', {
        ...this.queryParams
      }, `deviceGateway_${new Date().getTime()}.xlsx`)
    },
    /**
     * 启停状态修改
     */
    handleStartStopChange(row) {
      let text = row.startState === 'enabled' ? '启动' : '停止'
      this.$modal.confirm(`确认要${text}${row.gatewayName}网关吗？`).then(function() {
        if (row.startState === 'enabled') {
          startupDeviceGateway(row.id)
        }
        if (row.startState === 'disabled') {
          shutdownDeviceGateway(row.id)
        }
      }).then(() => {
        this.$modal.msgSuccess(`${text}成功`)
      }).catch(() => {
        row.startState = row.startState === 'enabled' ? 'disabled' : 'enabled'
      })
    },
    /**
     * 根据设备网关类型显示隐藏表单
     * @param type 设备网关类型
     */
    visibleByDeviceGatewayType(type) {
      if (!type) {
        // 网关名称
        this.protocolVisible = false
        //topics
        this.topicsVisible = false
        // Qos
        this.qosVisible = false
        return
      }

      if (type === 'mqtt-server-gateway') {
        // 网关名称
        this.protocolVisible = true
        //topics
        this.topicsVisible = false
        // Qos
        this.qosVisible = false
        return
      }

      if (type === 'mqtt-client-gateway') {
        // 网关名称
        this.protocolVisible = true
        //topics
        this.topicsVisible = true
        // Qos
        this.qosVisible = true
        return
      }

      if (type === 'tcp-server-gateway' || type === 'tcp-client-gateway') {
        // 网关名称
        this.protocolVisible = true
        //topics
        this.topicsVisible = false
        // Qos
        this.qosVisible = false
      }
    },
    getNetwork() {

      let provider = this.providers.find(item => item.id === this.form.provider)
      if (!provider) {
        return
      }

      queryNetwork({ type: provider.networkType.value })
        .then(({ data = [] }) => {
        this.networkConfig = data
      })
    },

    /** 获取支持的设备网关*/
    getProviders() {
      return new Promise((resolve) => {
        getProviders().then(({ data }) => {
          this.providers = data || []
          resolve(data)
        })
      })
    },

    /** providerMap 添加数据*/
    setProviderMap(data) {
      if (!Array.isArray(data)) {
        return
      }

      data.forEach(item => {
        this.providerMap[item.id] = item
      })

    },

    getTableProvider(provider) {

      if (!provider || !this.providerMap[provider]) {
        return
      }

      return this.providerMap[provider].name
    },

    /** 获取信息信息 */
    getProtocols() {
      queryProtocol().then(({ data }) => {
        this.protocols = data || []
      })
    },

    /** 重置网络组件下拉框 */
    resetNetworkSelect() {
      this.form.networkId = undefined
    }

  }
}
</script>

<style lang="scss" scoped>

</style>
